package com.qdev.apps.core.persistence.impl.type;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.UserType;

/**
 * @author Quake Wang
 * @since 2004-11-23
 * @version $Revision: 1.7 $
 */
public class StringArrayType implements UserType {
    protected static final String DELIMITER = ",";

    private static final int[] SQL_TYPES = new int[] { Hibernate.STRING.sqlType() };

    public int[] sqlTypes() {
        return SQL_TYPES;
    }

    public Class returnedClass() {
        return String[].class;
    }

    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y)
            return true;
        if (x == null || y == null)
            return false;
        return x.equals(y);
    }

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
        String s = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);
        if (s != null)
            return s.split(getDelimiterForSplit());
        return null;
    }

    public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        String[] s = (String[]) value;
        if (s != null) {
            Hibernate.STRING.nullSafeSet(st, join(s), index);
        } else {
            Hibernate.STRING.nullSafeSet(st, null, index);
        }
    }

    protected String join(String[] s) {
        List pieces = Arrays.asList(s);

        StringBuffer result = new StringBuffer();
        for (Iterator iter = pieces.iterator(); iter.hasNext();) {
            String string = (String) iter.next();
            if (string != null) {
                result.append(string);
                if (iter.hasNext())
                    result.append(getDelimiterForJoin());
            }
        }
        return result.toString();
    }

    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }

    public boolean isMutable() {
        return false;
    }

    protected String getDelimiterForSplit() {
        return DELIMITER;
    }

    protected String getDelimiterForJoin() {
        return DELIMITER;
    }
}